
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertest/models/route_model.dart';
import 'package:fluttertest/models/task_model.dart';
import 'package:fluttertest/navigation_result.dart';
import 'package:fluttertest/screens/delivery/delivery_form_screen.dart';
import 'package:fluttertest/utils/http_client.dart';

import '../../services/navigation_service.dart';
import '../../utils/event_bus.dart';
import '../delivery/summary_screen.dart';


class TaskDetailScreen extends StatefulWidget {
  TaskModel taskModel;


  TaskDetailScreen({super.key, required this.taskModel});

  @override
  State<TaskDetailScreen> createState() => _TaskDetailScreenState();
}

class _TaskDetailScreenState extends State<TaskDetailScreen> {
  bool _isInfoExpanded = false;
   RouteModel? _routeModel ;
  bool _isLoading = false;
  StreamSubscription? _subscription;



  @override
  void initState() {
    super.initState();
    _subscription = eventBus.onTaskStatusChanged.listen((_) {
      print("列表收到");
      _loadRoutes();
    });

    _loadRoutes().then((onValue)=>{
      if(widget.taskModel.status==5){
        Navigator.push(context, MaterialPageRoute(builder: (context) => SummaryScreen(waybillNumber: widget.taskModel.waybillNumber)))
      },
      if(_routeModel?.next?.status==2&&_routeModel?.next?.unArrival!=1){
        Navigator.push(context, MaterialPageRoute(builder: (context)=>DeliveryFormScreen(sequence: _routeModel!.next!,over: _routeModel!.over,)))
      }
    });
  }

  Future<void> _loadRoutes() async {
    if(mounted){
      setState(() {
        _isLoading = true;
      });
    }


    try {
      final response = await HttpClient.dio.post(
        '/follower/getRouteList',
        data: {
          'waybillNumber': widget.taskModel.waybillNumber,
        },
      );
      print(response.data);
      if (response.data['code'] == 0) {
        setState(() {
          _routeModel = RouteModel.fromJson(response.data['data'] ?? {});
          _isLoading = false;
          // _currentStoreIndex = _routeModel!.next!.index-1;
          // for(var i in _routeModel!.steps){
          //   print(i.index);
          // }
        });
      // } else {
        setState(() {
          _isLoading = false;
        });
      }else{
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '加载失败')),
          );
        }
      }
    } catch (e) {
      print("getroutelist${e}");
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }

  // Future<void> _adjustRoute(List<RouteModel> routeList, int selectId) async {
  //   try {
  //     final response = await HttpClient.dio.post(
  //       '/follower/adjustmentMerge',
  //       data: {
  //         'routeList': routeList,
  //         'selectId': selectId,
  //       },
  //     );
  //
  //     if (response.data['success'] == true) {
  //       await _loadRoutes();  // 重新加载路线
  //     } else {
  //       if (mounted) {
  //         ScaffoldMessenger.of(context).showSnackBar(
  //           SnackBar(content: Text(response.data['msg'] ?? '调整失败')),
  //         );
  //       }
  //     }
  //   } catch (e) {
  //     if (mounted) {
  //       ScaffoldMessenger.of(context).showSnackBar(
  //         const SnackBar(content: Text('网络错误，请稍后重试')),
  //       );
  //     }
  //   }
  // }

  Future<void> _navigateToStore(String shopCode) async {
    try {
      final response = await HttpClient.externalDio.get(
        'http://47.93.6.88/navcation/getLocation',
        queryParameters : {
          'shopCode': shopCode,
        },
      );
      print(response.data);
      // {code: 0, data: {shopCode: 3938, shopName: 朔州万和城A区店(撤), latitude: 39.32903, longitude: 112.441762, addr: 山西省朔州市朔城区建设北路34号靠近馨乐琴行(星乐音乐培训中心二部), name: null, createTime: 2022-09-18 13:46:49.0}}
      if (response.data['code'] == 0) {
        final location = response.data['data'];
        await NavigationService.navigateTo(
          double.parse(location['latitude'].toString()),
          double.parse(location['longitude'].toString()),
          location['shopName'].toString(),  // 使用店铺名称作为地址
        );
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '获取位置失败')),
          );
        }
      }
    } catch (e) {
      print(e);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('任务${widget.taskModel.loadingNumber}'),
      ),
      body: Column(
        children: [
          _buildProgressBar(),
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  Card(
                    child: ExpansionTile(
                      title: const Text('发车详情'),
                      initiallyExpanded: _isInfoExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          _isInfoExpanded = expanded;
                        });
                      },
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            children: [
                              _buildInfoRow('司机', widget.taskModel.driverName),
                              _buildInfoRow('查询人', widget.taskModel.followerName),
                              _buildInfoRow('车牌号', widget.taskModel.carCode),
                              _buildInfoRow('门店数量', '${widget.taskModel.storeCount}家'),
                              _buildInfoRow('装车单号', widget.taskModel.loadingNumber),
                              _buildInfoRow('查询号', widget.taskModel.waybillNumber),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 16),
                  _buildStoresView(),
                ],
              ),
            ),
          ),
          if ( widget.taskModel.status == 1)
            Padding(
              padding: const EdgeInsets.all(28),
              child: ElevatedButton(
                onPressed: _onLoadingComplete,
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size.fromHeight(48),
                ),
                child: const Text('装车完成'),
              ),
            ),

          if (widget.taskModel.status == 2)
            Padding(
              padding: const EdgeInsets.all(28),
              child: ElevatedButton(
                onPressed: _onCheckComplete,
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size.fromHeight(48),
                ),
                child: const Text('确认无误，开始发车'),
              ),
            ),
          if (_routeModel?.next!=null&&widget.taskModel.status==3)  // 发车状态且未完成所有店铺
            Padding(
              padding: const EdgeInsets.all(28),
              child: Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed:_isLoading?null: _onDeliveryComplete,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,
                      ),
                      child: Text('到达${_routeModel?.next!.storeNumber}号店',style: TextStyle(color: Colors.white),),
                    ),
                  ),
                  // const SizedBox(width: 16),
                  // Expanded(
                  //   child: OutlinedButton(
                  //     onPressed: _onNavigateToStore,
                  //     child: const Text('导航到店'),
                  //   ),
                  // ),
                ],
              ),
            ),
          if (_routeModel?.over == true && widget.taskModel.status==4)  // 发车状态且完成所有店铺
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: ElevatedButton(
                onPressed: _onArrivalCenter,
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size.fromHeight(48),
                ),
                child: const Text('到达物流中心'),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildProgressBar() {
    const allStatuses = ['装车', '发车', '到店', '回车'];
    final currentState = widget.taskModel.status;
    // 1 2 3 4 5 6

    // 明天需要做进度的显示 现在到发车 线条亮 数字不亮
    return Container(
      padding: const EdgeInsets.all(16),
      color: Colors.orange.shade50,
      child: Column(
        children: [
          Row(
            children: List.generate(allStatuses.length * 2 - 1, (index) {
              int currentIndex = index ~/ 2;
              // 0 1 1 2 2 3 3 4
              if (index.isOdd) {
                return Expanded(
                  child: Container(
                    height: 2,
                    color: currentIndex < currentState-1
                        // 0 1 2 3 4 5
                        ? Colors.green 
                        : Colors.grey.shade300,
                  ),
                );
              }
              //                  3                5
              final isCompleted = currentIndex < currentState-1;
              final isCurrent = currentIndex == currentState-1;

              return Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: isCompleted 
                      ? Colors.green 
                      : isCurrent 
                          ? Colors.orange 
                          : Colors.grey.shade300,
                ),
                child: Icon(
                  isCompleted ? Icons.check : Icons.circle,
                  size: 16,
                  color: Colors.white,
                ),
              );
            }),
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: allStatuses.map((status) {
              final isCompleted = allStatuses.indexOf(status) < currentState;
              final isCurrent = widget.taskModel.status == currentState;
              return Text(
                status,
                style: TextStyle(
                  color: isCompleted 
                      ? Colors.green
                      : isCurrent 
                          ? Colors.orange 
                          : Colors.grey,
                  fontWeight: isCurrent ? FontWeight.bold : FontWeight.normal,
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  Widget _buildStoresView() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    return Card(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                Text(
                  widget.taskModel.status == 2 ? '核对店铺信息' : '送货路线',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                if (widget.taskModel.status == 3 )
                  Text(
                    '当前: ${_routeModel?.next?.storeName??'已全部到达'}',
                    style: const TextStyle(
                      color: Colors.orange,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
              ],
            ),
          ),
          const Divider(height: 1),
          _routeModel?.over==false
              ? ReorderableListView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: _routeModel!.steps.length,
                  onReorder: _onReorderStores,
                  itemBuilder: (context, index) {
                    final route = _routeModel!.steps[index];
                    return ListTile(
                      key: Key('store_${route?.id}'),
                      leading: CircleAvatar(
                        backgroundColor: _routeModel!.next!.id == route.id
                            ? Colors.orange
                            : route!.status>=3&&route!.unArrival!=1
                            ? Colors.green
                            : route!.status<=2&&route!.unArrival==1
                            ? Colors.red
                            : Colors.grey,
                        child: Text('${index + 1}'),
                      ),
                      title: Text(route!.storeName),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('店号: ${route!.storeNumber}'),
                        ],
                      ),
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text('周转箱${route!.realTrunBox} 箱'),
                          ...[
                            const SizedBox(width: 8),
                            IconButton(
                              icon: const Icon(Icons.navigation),
                              onPressed: () => _navigateToStore(route!.storeNumber),
                            ),
                          ],
                        ],
                      ),
                      isThreeLine: true,
                    );
                  },
                )
              : ListView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: _routeModel!.steps.length,
                  itemBuilder: (context, index) {
                    final route = _routeModel!.steps[index];
                    return ListTile(
                      key: Key('store_${route!.id}'),
                      leading: CircleAvatar(
                        backgroundColor: route!.status>=3&&route!.unArrival!=1
                            ? Colors.green
                            : route!.status<=2&&route!.unArrival==1
                            ? Colors.red
                            : Colors.grey,
                        child: Text('${index + 1}'),
                      ),
                      title: Text(route!.storeName),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('店号: ${route!.storeNumber}'),
                        ],
                      ),
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text('${route.realTrunBox} 箱'),
                          if (route.unArrival==1) ...[
                            const SizedBox(width: 8),
                            IconButton(
                              icon: const Icon(Icons.navigation),
                              onPressed: () => _navigateToStore(route.storeNumber),
                            ),
                          ],
                        ],
                      ),
                      isThreeLine: true,
                    );
                  },
                ),
        ],
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: const TextStyle(color: Colors.grey),
            ),
          ),
          Expanded(child: Text(value)),
        ],
      ),
    );
  }

  void _onLoadingComplete() async {
      final response = await HttpClient.dio.post(
        '/follower/loaded',
        data: {
          'waybillNumber': widget.taskModel.waybillNumber,
        },
      );

      if (response.data['code'] == 0) {
        setState(() {
          widget.taskModel = TaskModel.fromJson(response.data['data']);  // 装车完成后进入检查阶段
        });
        await _loadRoutes();
        eventBus.notifyTaskStatusChanged();
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '装车确认失败')),
          );
        }
      }
  }

  void _onCheckComplete() async {
      final response = await HttpClient.dio.post(
        '/follower/setOut',
        data: {
          'waybillNumber': widget.taskModel.waybillNumber,
        },
      );
      if (response.data['code'] == 0) {
        setState(() {
          widget.taskModel = TaskModel.fromJson(response.data['data']);
        });
        await _loadRoutes();
        eventBus.notifyTaskStatusChanged();
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '发车确认失败')),
          );
        }
      }
  }

  Future<void> _onDeliveryComplete() async {
    if(mounted){
      setState(() {
        _isLoading = true;
      });
    }
    final response = await HttpClient.dio.post(
      '/follower/arrivalStore',
      data: {
        'id':_routeModel!.next!.id,
      },
    );
    // final response = await HttpClient.dio.post(
    //   '/follower/arrivalStore',
    //   data: {
    //     'storeNumber':_routeModel!.next!.storeNumber,
    //     'waybillNumber': widget.taskModel.waybillNumber,
    //   },
    // );
    if (response.data['code'] == 0) {
      final result = await Navigator.push<NavigationResult>(context, MaterialPageRoute(builder: (context)=>DeliveryFormScreen(sequence: _routeModel!.next!,over: _routeModel!.over,)));
      if (result != null) {
        if (result.message != null) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(result.message!)),
          );
        }
        if (result.popToRoot) {
          if (mounted) {
            Navigator.of(context).popUntil((route) => route.isFirst);
          }
        } else if (result.needRefresh) {
          await _loadRoutes();  // 刷新当前页面数据
          print(_routeModel?.over);
          if (mounted) {
            Navigator.of(context).popUntil((route) => route.isFirst);
          }
        }else if(result.skip!){
          await _loadRoutes();  // 刷新当前页面数据
        }
      }
      await _loadRoutes();
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(response.data['msg'] ?? '到达${_routeModel?.next?.storeNumber}号店失败')),
        );
      }
    }
  }

  void _onNavigateToStore() {
    // TODO: 实现导航功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('正在打开导航...')),
    );
  }

  void _onReorderStores(int oldIndex, int newIndex) async {
    print('${oldIndex},${newIndex}');
    if (!(newIndex==_routeModel!.steps.indexWhere((e)=>e.status<=1&&e.unArrival!=1))) {
      // 如果不是移动到下一个位置，就取消操
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('只能将店铺移动到下一家要送门店的上方')),
      );
      return;
    }

    try {
      // 调用调整路线的 API
      final response = await HttpClient.dio.post(
        '/follower/adjustment',
        data: {
          'selectId': _routeModel!.steps[oldIndex].id,
          'routeList': _routeModel!.toJson(),  // 转换为字符串
        },
      );
      if (response.data['code'] == 0) {
        setState(() {
          final item = _routeModel!.steps.removeAt(oldIndex);
          _routeModel!.steps.insert(newIndex, item);
        });
        // 重新加载路线信息以确保与服务器同步
        await _loadRoutes();
      } else {
        // 如果失败，回滚本地更改
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '调整顺序失败')),
          );
        }
      }
    } catch (e) {
      // 发生错误时，回滚本地更改
      await _loadRoutes();  // 重新加载以恢复原始顺序
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }


  Future<void> _onArrivalCenter() async {
    try {
      final response = await HttpClient.dio.post(
        '/follower/arrivalCenter',
        data: {
          'waybillNumber': widget.taskModel.waybillNumber,
        },
      );

      if (response.data['code'] == 0) {
        // 跳转到汇总页面
        if (mounted) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => SummaryScreen(waybillNumber: widget.taskModel.waybillNumber),
            ),
          );
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['message'] ?? '操作失败')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }
}